package ontime

import (
	"encoding/json"
	"io"
	"os"
)

// now，there is no good idea to serial a function,so，i decided to abandon this feature
var fileName string = "7628A959-183F-4B16-96B2-E8A2BCF0BC26_ON_TIME.json"

type Store interface {
	Write(data interface{}) error
	Read() ([]*Entry, error)
}

type FileStore struct{}

func NewFileStore() Store {
	return FileStore{}
}

func (fs FileStore) Write(data interface{}) error {
	buff, err := json.Marshal(data)
	if err != nil {
		return err
	}
	f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = f.Write(buff)
	return err
}
func (fs FileStore) Read() ([]*Entry, error) {
	f, err := os.Open(fileName)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	buff, err := io.ReadAll(f)
	if err != nil {
		return nil, err
	}
	entries := make([]*Entry, 0)
	err = json.Unmarshal(buff, &entries)
	return entries, err
}
